package main

import (
	"encoding/json"
	"gitee.com/geektime/geek-go-practise/metrics"
	"github.com/golang/glog"
	"github.com/google/uuid"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"io"
	"math/rand"
	"net/http"
	"os"
	"time"
)

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
	gw := &GlogResponseWriter{
		ResponseWriter: w,
		StatusCode:     200,
		id:             uuid.NewString(),
	}
	glog.Infof("[%s] Request URL: %s, Request IP: %s", gw.id, r.URL, r.RemoteAddr)

	router := http.NewServeMux()
	router.Handle("/echo", http.HandlerFunc(EchoRequestHeaderAndVersion))
	router.Handle("/healthz", http.HandlerFunc(CheckServerHealth))
	router.Handle("/metrics", promhttp.Handler())
	router.ServeHTTP(gw, r)
	glog.Infof("[%s] Response statusCode: %d", gw.id, gw.StatusCode)

}

func EchoRequestHeaderAndVersion(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	delay := RandInt(10, 2000)
	time.Sleep(time.Millisecond * time.Duration(delay))
	for k, values := range r.Header {
		for v := range values {
			w.Header().Add(k, values[v])
		}
	}
	w.Header().Set("VERSION", os.Getenv("VERSION"))
	headerJson, _ := json.Marshal(w.Header())
	_, err := w.Write(headerJson)
	if err != nil {
		return
	}
	w.WriteHeader(200)
}

func CheckServerHealth(w http.ResponseWriter, r *http.Request) {
	_, err := io.WriteString(w, "ok")
	if err != nil {
		return
	}
	w.WriteHeader(200)
}

func RandInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}
